using System;
using System.Collections.Generic;
using System.Text;
using ECommerce.Library.Mail;
using Entity;
using ECommerce.DAL;
using System.Collections.Specialized;
using log4net;
using ECommerce.Library;
using System.IO;
using System.Web;
using B2C.Utilities;


namespace AutoGear.BLL
{
    public class Email
    {
        private const string _invoiceEmailTemplateFilePath = "~/templates/invoice-email-template.txt";

        public static bool SendGenericEmail(string toName, string toEmail, string subject, string body)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailText = body;
                string mailSubject = SiteSettings.CompanyName + " : " + subject;
                NameValueCollection items = new NameValueCollection();
                
                items.Add("ReceiverName", toName);
                items.Add("ReceiverEmail", toEmail);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                //Emailer.SendMail(toEmail, SiteSettings.AdminEmail, SiteSettings.CompanyName, subject, body);
                return true;

            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("Generic Email caused server error: Parameters( ");

                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("Email");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;
            }
        }

        public static bool SendRegistrationEmail(CustomerUser customerUser)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.RegistrationEmail.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  New  Registration";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##FirstName##>", customerUser.Profile.FirstName);
                    mailText = mailText.Replace("<##LastName##>", customerUser.Profile.LastName);
                    mailText = mailText.Replace("<##Address1##>", customerUser.Profile.BillingAddress.AddressLine1);
                    mailText = mailText.Replace("<##Address2##>", customerUser.Profile.BillingAddress.AddressLine2);
                    mailText = mailText.Replace("<##City##>", customerUser.Profile.BillingAddress.City);
                    mailText = mailText.Replace("<##State##>", customerUser.Profile.BillingAddress.AddressState);
                    mailText = mailText.Replace("<##Country##>", customerUser.Profile.BillingAddress.AddressCountry);
                    mailText = mailText.Replace("<##Zip##>", customerUser.Profile.BillingAddress.ZipCode);
                    mailText = mailText.Replace("<##Phone##>", customerUser.Profile.UserTelephoneNumber);
                    mailText = mailText.Replace("<##PersonalEmailAddress##>", customerUser.Profile.EmailAddress);
                    mailText = mailText.Replace("<##LoginEmailAddress##>", customerUser.LoginUserName);
                    mailText = mailText.Replace("<##LoginPasswords##>", customerUser.LoginPassword);
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                    mailText = mailText.Replace("<##LoginPage##>", SiteSettings.SiteBaseUrl +"login.aspx");

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", customerUser.DisplayName);
                    items.Add("ReceiverEmail", customerUser.Profile.EmailAddress);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;

            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("SendRegistrationEmail caused server error: Parameters( ");

                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("Email");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;

            }
        }

        public static bool SendRegistrationEmailToAdmin(CustomerUser customerUser)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.RegistrationEmailAdmin.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  New  Registration";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##FirstName##>", customerUser.Profile.FirstName);
                    mailText = mailText.Replace("<##LastName##>", customerUser.Profile.LastName);
                    mailText = mailText.Replace("<##Address1##>", customerUser.Profile.BillingAddress.AddressLine1);
                    mailText = mailText.Replace("<##Address2##>", customerUser.Profile.BillingAddress.AddressLine2);
                    mailText = mailText.Replace("<##City##>", customerUser.Profile.BillingAddress.City);
                    mailText = mailText.Replace("<##State##>", customerUser.Profile.BillingAddress.AddressState);
                    mailText = mailText.Replace("<##Country##>", customerUser.Profile.BillingAddress.AddressCountry);
                    mailText = mailText.Replace("<##Zip##>", customerUser.Profile.BillingAddress.ZipCode);
                    mailText = mailText.Replace("<##Phone##>", customerUser.Profile.UserTelephoneNumber);
                    mailText = mailText.Replace("<##PersonalEmailAddress##>", customerUser.Profile.EmailAddress);
                    mailText = mailText.Replace("<##LoginEmailAddress##>", customerUser.LoginUserName);
                    mailText = mailText.Replace("<##LoginPasswords##>", customerUser.LoginPassword);
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", SiteSettings.SiteName);
                    items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("SendRegistrationEmailToAdmin caused server error: Parameters( ");

                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("Email");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;

            }
        }

        public static bool SendPasswordRecoverEmail(CustomerUser customerUser)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.PasswordRecoverEmail.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  Your Password";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##FirstName##>", customerUser.Profile.FirstName);
                    mailText = mailText.Replace("<##LoginEmailAddress##>", customerUser.LoginUserName);
                    mailText = mailText.Replace("<##LoginPasswords##>", customerUser.LoginPassword);
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                    mailText = mailText.Replace("<##LoginPage##>", SiteSettings.SiteBaseUrl + "login.aspx");

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", customerUser.DisplayName);
                    items.Add("ReceiverEmail", customerUser.Profile.EmailAddress);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("SendPasswordRecoverEmail caused server error: Parameters( ");

                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("Email");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;

            }
        }

        public static bool SendCouponEmail(Address billingAddress, Coupon coupon, string message, List<string> emailRecipients)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = billingAddress.EmailAddress;
                mailSettings.SupportMail = billingAddress.EmailAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                StringBuilder mailBody = new StringBuilder();
                string mailSubject = SiteSettings.CompanyName + " :  Your friend has sent you a coupon";

                mailBody.Append("Your friend ").Append(billingAddress.FirstName + " " + billingAddress.LastName).Append(" has sent you a coupon: ").Append(coupon.CouponName).Append("<br/><br/>");
                mailBody.Append("Coupon Code: ").Append(coupon.CouponName).Append("<br/><br/>");
                mailBody.Append("Coupon: ");
                if (coupon.CouponType == CouponType.Text)
                {
                    mailBody.Append("<p>").Append(coupon.CouponDescription).Append("</p>").Append("<br/>");

                }
                else
                {
                    mailBody.Append("<img width='100px' src='").Append(coupon.CouponImageUrl).Append("'/>").Append("<br/>");
                }
                if (coupon.CalculationIn == CouponCalculationIn.Dollar)
                {
                    mailBody.Append("Available Discount: ").Append(ECommerce.Library.ECommerce.Utility.FormatPriceText(coupon.CouponAmount)).Append("<br/><br/>");
                }
                else
                {
                    mailBody.Append("Available Discount: ").Append(ECommerce.Library.ECommerce.Utility.FormatPercentage(coupon.CouponAmount)).Append("<br/><br/>");
                }
                //mailBody.Append("Please follow the link to know more detail: ").Append("http://72.32.173.113/public/coupon-received.aspx?coupon=").Append(coupon.CouponId.ToString()).Append("<br/><br/><br/><br/>");

                mailBody.Append("Your friend wrote: ").Append(message).Append("<br/><br/>");

                foreach (string email in emailRecipients)
                {
                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", email);
                    items.Add("ReceiverEmail", email);
                    items.Add("Subject", mailSubject);

                    MailSender.SendHtmlMaill(mailSettings, mailBody.ToString(), items);
                }

                return true;


            }
            catch (Exception ex)
            {

                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("SendPasswordRecoverEmail caused server error: Parameters( ");

                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("Email");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);
                throw ex;

            }
        }

        public static bool SendInvoiceEmail(ProductPurchaseOrder order,String brandImageUrl)
        {
            try
            {
                Address billingAddress = (Address)order.BillingAddress;
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailText = GenerateInvoiceEmailBody(order,brandImageUrl);
                string mailSubject = SiteSettings.CompanyName + " :  Receipt for Order Number " + order.OrderNumber;

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", billingAddress.FirstName + " " + billingAddress.LastName);
                items.Add("ReceiverEmail", billingAddress.EmailAddress);
                items.Add("Subject", mailSubject);
                
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                items.Clear();

                items.Add("ReceiverName", "Administrator");
                items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                items.Add("Subject", mailSubject);
                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                // Send Incoice to Admin
                

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static bool SendMultipleInvoiceEmail(ProductPurchaseOrder order)
        {
            try
            {
                Address billingAddress = (Address)order.BillingAddress;
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                string mailText = GenerateMultipleInvoiceEmailBody(order);
                string mailSubject = SiteSettings.CompanyName + " :  Receipt for Order Number " + order.OrderNumber;

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", billingAddress.FirstName + " " + billingAddress.LastName);
                items.Add("ReceiverEmail", billingAddress.EmailAddress);
                items.Add("Subject", mailSubject);

                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string GenerateMultipleInvoiceEmailBody(ProductPurchaseOrder order)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(_invoiceEmailTemplateFilePath)))
            {
                try
                {
                    StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_invoiceEmailTemplateFilePath));
                    string templateContent = reader.ReadToEnd();
                    reader.Close();
                    string val = string.Empty;

                    templateContent = templateContent.Replace("<##OrderNumber##>", order.OrderNumber);
                    templateContent = templateContent.Replace("<##ReceiptDate##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(order.OrderDate));
                    templateContent = templateContent.Replace("<##BillingEmailAddress##>", order.BillingAddress.EmailAddress);
                    templateContent = templateContent.Replace("<##BillingFirstName##>", order.BillingAddress.FirstName);
                    templateContent = templateContent.Replace("<##BillingLastName##>", order.BillingAddress.LastName);
                    templateContent = templateContent.Replace("<##BillingAddressLine1##>", order.BillingAddress.AddressLine1);
                    templateContent = templateContent.Replace("<##BillingAddressLine2##>", order.BillingAddress.AddressLine2);
                    templateContent = templateContent.Replace("<##ShippingEmailAddress##>", order.ShippingAddress.EmailAddress);
                    templateContent = templateContent.Replace("<##ShippingFirstName##>", order.ShippingAddress.FirstName);
                    templateContent = templateContent.Replace("<##ShippingLastName##>", order.ShippingAddress.LastName);
                    templateContent = templateContent.Replace("<##ShippingAddressLine1##>", order.ShippingAddress.AddressLine1);
                    templateContent = templateContent.Replace("<##ShippingAddressLine2##>", order.ShippingAddress.AddressLine2);
                    templateContent = templateContent.Replace("<##Subtotal##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ShoppingCart.SubTotal + order.ShoppingCart.GiftSubTotal));
                    templateContent = templateContent.Replace("<##CouponDiscount##>", "-" + ECommerce.Library.ECommerce.Utility.FormatPriceText(order.CouponDiscount));
                    templateContent = templateContent.Replace("<##ShippingCost##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ProductShipping.ProductShippingCost));
                    templateContent = templateContent.Replace("<##Tax##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.TaxAmount));
                    TblProductPurchaseOrder temporder = TblProductPurchaseOrder.GetTblProductPurchaseOrderByOrderId(order.OrderId);
                    if (temporder != null)
                        templateContent = templateContent.Replace("<##TotalAmount##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(temporder.OrderPrice + temporder.ShippingCost + temporder.TaxAmount - temporder.CouponDiscount));
                    //templateContent = templateContent.Replace("<##giftCardImage##>", SiteSettings.SiteBaseUrl + order.GiftCardImageUrl.Replace("~/",""));
                    //templateContent = templateContent.Replace("<##giftCardMsg##>",order.GIftCardMessage);
                    templateContent = templateContent.Replace("<##TermsAndConditionsPage##>", SiteSettings.SiteBaseUrl + "terms-and-conditions.aspx");
                    templateContent = templateContent.Replace("<##SupportPage##>", SiteSettings.SiteBaseUrl + "contact-us.aspx");
                    templateContent = templateContent.Replace("<##AccountInformationPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                    templateContent = templateContent.Replace("<##PurchaseHistoryPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                    templateContent = templateContent.Replace("<##PrivacyPolicyPage##>", SiteSettings.SiteBaseUrl + "privacy-policy.aspx");

                    templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    templateContent = templateContent.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    templateContent = templateContent.Replace("<##SiteName##>", SiteSettings.SiteName);

                    if (order.PaymentType == PaymentType.CreditCard)
                        val = "Credit Card";
                    else if (order.PaymentType == PaymentType.GiftCoupon)
                        val = "Gift Certificate";
                    else
                        val = "Credit Card & Gift Certificate";

                    templateContent = templateContent.Replace("<##PaymentType##>", val);

                    val = (order.OrderStatus == OrderStatus.CCSuccess) ? "Success" : "Failed";
                    templateContent = templateContent.Replace("<##OrderStatus##>", val);
                    if (val == "Success")
                        templateContent = templateContent.Replace("<##Color##>", "Green");
                    else
                        templateContent = templateContent.Replace("<##Color##>", "Red");

                    string giftCard = string.Empty;
                    if (order.GiftCardImageUrl.Length > 0)
                    {
                        giftCard = " <span><strong> Gift Card </strong></span> <br/><br /> " +
                                    " <img  src=" + SiteSettings.SiteBaseUrl + order.GiftCardImageUrl.Replace("~/", "") + " width=\"190\" height=\"70\" /><br /><br /> " + order.GIftCardMessage + "<br />";
                        templateContent = templateContent.Replace("<##GiftCard##>", giftCard);
                    }
                    else
                    {
                        templateContent = templateContent.Replace("<##GiftCard##>", "");
                    }
                    string orderItems = string.Empty;
                    foreach (CartItem item in order.ShoppingCart.CartItems)
                    {
                        string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                            + item.Product.ItemNumber + "</td><td style=\"text-align: left\">"
                            + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                        + item.Product.ProductName + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" />"
                        + "</td><td style=\"text-align: right;\">" +
                        ECommerce.Library.ECommerce.Utility.FormatPriceText(item.Product.ProductPrice) + "</td></tr>";
                        orderItems += temp;
                    }
                    templateContent = templateContent.Replace("<##OrderItems##>", orderItems);


                    string giftItems = string.Empty;
                    foreach (GiftItem item in order.ShoppingCart.GiftItems)
                    {
                        string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                            + item.FromName + "</td><td style=\"text-align: left\">"
                            + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                        + item.FromEmailAddress + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" />"
                        + "</td><td style=\"text-align: right;\">" +
                        ECommerce.Library.ECommerce.Utility.FormatPriceText(item.ItemTotal) + "</td></tr>";
                        giftItems += temp;
                    }
                    templateContent = templateContent.Replace("<##GiftCertificate##>", giftItems);

                    string featuredItems = string.Empty;
                    ECommerce.Library.DataStructure.ReadWriteCustomCollection<Product> featuredProducts = Product.FeaturedProducts(3);

                    if (featuredProducts != null && featuredProducts.Count > 0)
                    {
                        featuredItems = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >"
                                        + "<tr><td><img alt=\"Recommendations\" src=\"<##SiteUrl##>images/recommend.gif\" width=\"180\" border=\"0\" height=\"33\" /></td></tr>"
                                        + "<tr style=\"background-color:#f5f4f4;border-left: solid 1px #D0D0D0;border-right: solid 1px #D0D0D0\"><td >"
                                        + "<table style=\"width: 100%;text-align: center;padding-top: 10px;\" cellpadding=\"0\" cellspacing=\"0\" >";
                        foreach (Product item in featuredProducts)
                        {
                            string temp = "<tr><td style=\"vertical-align: top;\">"
                               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\" >"
                               + "<tr><td style=\"text-align: center; vertical-align: top\">"
                               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\">"
                               + "<tr><td style=\"border: 1px solid #cccccc; padding: 0px;\">"
                               + "<a href=\"" + SiteSettings.SiteBaseUrl + item.ProductUrl.Replace("~/", "") + "\" target=\"_blank\"><img src=\""
                               + SiteSettings.SiteBaseUrl + ImageResizer.CheckImageMissing(item.ProductImageSmallThumbnail, SiteSettings.NoImageSmallThumbnailUrl).Replace("~/", "") + "\" width=\"60\" height=\"60\" border=\"0\" /></a>"
                               + "</td></tr></table></td></tr><tr>"
                               + "<td style=\"text-align: center; color: #000000;\" valign=\"top\">"
                               + "<a href=\"" + SiteSettings.SiteBaseUrl + item.ProductUrl.Replace("~/", "") + "\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                               + item.ProductName + "</a></b></td>"
                              + "</tr></table></td></tr><tr><td style=\"vertical-align: top;\">&nbsp;</td></tr>";
                            featuredItems += temp;
                        }
                        featuredItems += "</table></td></tr><tr><td>"
                            + "<img alt=\"Box Bottom\" src=\"<##SiteUrl##>images/box_bevel_180_botfull.gif\" width=\"180\" border=\"0\" height=\"12\" />"
                            + "</td></tr></table>";

                    }

                    templateContent = templateContent.Replace("<##FeaturedItems##>", featuredItems);
                    templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    return templateContent;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return string.Empty;
        }
        public static bool SendInvoiceEmailFromAdmin(string ReceiverEmail,string ReceiverName,string Subject, ProductPurchaseOrder order)
        {
            try
            {
                Address billingAddress = (Address)order.BillingAddress;
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;
                
                string mailText = GenerateInvoiceEmailBody(order);
                string mailSubject = SiteSettings.CompanyName + " :  Receipt for Order Number " + order.OrderNumber;

                NameValueCollection items = new NameValueCollection();
                items.Add("ReceiverName", ReceiverName);
                items.Add("ReceiverEmail", ReceiverEmail);
                items.Add("Subject", mailSubject);

                MailSender.SendHtmlMaill(mailSettings, mailText, items);
                return true;
               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool SendGiftCertificateEmail(ProductPurchaseOrder order)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.GiftCertificate.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " : Gift Certificate";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##Name##>", order.ShoppingCart.GiftItems[0].FromName);
                    mailText = mailText.Replace("<##ToName##>", order.ShoppingCart.GiftItems[0].ToName);
                    mailText = mailText.Replace("<##CreateDate##>",Convert.ToString(order.ShoppingCart.GiftItems[0].DateCreated.ToShortDateString()));
                    mailText = mailText.Replace("<##ExpiredDate##>", Convert.ToString(order.ShoppingCart.GiftItems[0].DateExpired.ToShortDateString()));
                    mailText = mailText.Replace("<##Amount##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ShoppingCart.GiftItems[0].ItemTotal));
                    mailText = mailText.Replace("<##Code##>", order.ShoppingCart.GiftItems[0].GiftCertificateCode);
                    mailText = mailText.Replace("<##Message##>", order.ShoppingCart.GiftItems[0].Message);
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteBaseUrl + "App_Style/images/gift-logo.png");
                    mailText = mailText.Replace("<##NewsletterLogo##>", SiteSettings.SiteBaseUrl + "App_Style/images/NewsletterLogo.png");
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                    mailText = mailText.Replace("<##Code##>",order.ShoppingCart.GiftItems[0].GiftCertificateCode);

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", order.ShoppingCart.GiftItems[0].ToName);
                    items.Add("ReceiverEmail", order.ShoppingCart.GiftItems[0].ToEmailAddress);

                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static bool SendInqueryEmailToAdmin(Inquires inquiry)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.InqueryEmailAdmin.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  New  Inquery";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##Name##>", inquiry.Name);
                    mailText = mailText.Replace("<##Organization##>", inquiry.Organization);
                    mailText = mailText.Replace("<##EmailAddress##>", inquiry.EmailAddress);
                    mailText = mailText.Replace("<##Telephone##>", inquiry.Telephone);
                    mailText = mailText.Replace("<##Subject##>", inquiry.Subject);
                    mailText = mailText.Replace("<##Website##>", inquiry.Website);
                    mailText = mailText.Replace("<##Inquiry##>", inquiry.Inquiry);
                    mailText = mailText.Replace("<##Date##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(inquiry.CreateDate));
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                    NameValueCollection items = new NameValueCollection();
                    //items.Add("ReceiverName", SiteSettings.SiteName);
                    //items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                    items.Add("ReceiverName", TblSettings.GetTblSettingsBySettingsId(1).CompanyName.ToString());
                    items.Add("ReceiverEmail", TblSettings.GetTblSettingsBySettingsId(1).CompanyEmail.ToString());
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool SendFormInfoEmailToAdmin(FreeRestringingForm freeRestringingForm)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.FormSubmission.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " : FormSubmission";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##Name##>", freeRestringingForm.UserName);
                    mailText = mailText.Replace("<##Date##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(freeRestringingForm.FormDate));
                    mailText = mailText.Replace("<##Address##>", freeRestringingForm.UserAddress);
                    mailText = mailText.Replace("<##Phone##>", freeRestringingForm.UserTelephoneNumber);
                    mailText = mailText.Replace("<##EmailAddress##>", freeRestringingForm.UserEmailAddress);
                    mailText = mailText.Replace("<##Length##>", freeRestringingForm.LengthOfNecklace);
                    mailText = mailText.Replace("<##Pearls##>", freeRestringingForm.TotalPearls);
                    mailText = mailText.Replace("<##Size##>", freeRestringingForm.SizeOfPearls);
                    mailText = mailText.Replace("<##Comments##>", freeRestringingForm.Comments);
                    mailText = mailText.Replace("<##SubDate##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(freeRestringingForm.CreateDate));
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                    NameValueCollection items = new NameValueCollection();
                    //items.Add("ReceiverName", SiteSettings.SiteName);
                    //items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                    items.Add("ReceiverName", TblSettings.GetTblSettingsBySettingsId(1).CompanyName.ToString());
                    items.Add("ReceiverEmail", TblSettings.GetTblSettingsBySettingsId(1).CompanyEmail.ToString());
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool SendStockAlertEmailToAdmin(StockAlert alert)
        {
            try
            {
                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.StockAlertEmailAdmin.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  Stock Alert";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##ItemNumber##>", alert.ProductItemNumber);
                    mailText = mailText.Replace("<##ProductName##>", alert.ProductName);
                    mailText = mailText.Replace("<##ProductSize##>", alert.ProductSize);
                    mailText = mailText.Replace("<##StockAmount##>", alert.StockAmount.ToString());
                    mailText = mailText.Replace("<##Date##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(DateTime.Now));
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", SiteSettings.SiteName);
                    items.Add("ReceiverEmail", SiteSettings.EmailAdminAddress);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool SendNewsletterEmail(Newsletter newsletter, out string fullEmailText)
        {
            try
            {
                fullEmailText = string.Empty;

                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                //CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.NewsletterEmail.ToString());
                //string mailText = string.Empty;
                //string mailSubject = SiteSettings.CompanyName + " :  Newsletter";
                //if (tblEmailTemplate.Count > 0)
                //{
                   
                //}

                //return false;

                string mailSubject = "E-Shop:  Newsletter";

                string mailText = newsletter.Body;

                foreach (NewsletterSubscriber subscriber in newsletter.Subscribers)
                {
                    NameValueCollection items = new NameValueCollection();
                    if (string.IsNullOrEmpty(subscriber.SubscriberName))
                        subscriber.SubscriberName = "Subscriber";
                    items.Add("ReceiverName", subscriber.SubscriberName);
                    items.Add("ReceiverEmail", subscriber.Email);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);

                }
                fullEmailText = mailText;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string PreviewNewsletterEmail(Newsletter newsletter)
        {
            try
            {
                //CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.NewsletterEmail.ToString());
                //string mailText = string.Empty;
                //string mailSubject = SiteSettings.CompanyName + " :  Newsletter";
                //if (tblEmailTemplate.Count > 0)
                //{
                //    mailText = tblEmailTemplate[0].EmailBody;
                //    mailSubject = tblEmailTemplate[0].EmailSubject;
                //    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                //    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                //    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                //    mailText = mailText.Replace("<##MessageBody##>", newsletter.Body);
                //    mailText = mailText.Replace("<##Subject##>", newsletter.Subject);

                //    return mailText;
                //}
                return newsletter.Body;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }


        private static string GenerateInvoiceEmailBody(ProductPurchaseOrder order)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(_invoiceEmailTemplateFilePath)))
            {
                try
                {
                    StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_invoiceEmailTemplateFilePath));
                    string templateContent = reader.ReadToEnd();
                    reader.Close();
                    string val = string.Empty;

                    templateContent = templateContent.Replace("<##OrderNumber##>", order.OrderNumber);
                    templateContent = templateContent.Replace("<##ReceiptDate##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(order.OrderDate));
                    templateContent = templateContent.Replace("<##BillingEmailAddress##>", order.BillingAddress.EmailAddress);
                    templateContent = templateContent.Replace("<##BillingFirstName##>", order.BillingAddress.FirstName);
                    templateContent = templateContent.Replace("<##BillingLastName##>", order.BillingAddress.LastName);
                    templateContent = templateContent.Replace("<##BillingAddressLine1##>", order.BillingAddress.AddressLine1);
                    templateContent = templateContent.Replace("<##BillingAddressLine2##>", order.BillingAddress.AddressLine2);
                    templateContent = templateContent.Replace("<##ShippingEmailAddress##>", order.ShippingAddress.EmailAddress);
                    templateContent = templateContent.Replace("<##ShippingFirstName##>", order.ShippingAddress.FirstName);
                    templateContent = templateContent.Replace("<##ShippingLastName##>", order.ShippingAddress.LastName);
                    templateContent = templateContent.Replace("<##ShippingAddressLine1##>", order.ShippingAddress.AddressLine1);
                    templateContent = templateContent.Replace("<##ShippingAddressLine2##>", order.ShippingAddress.AddressLine2);
                    templateContent = templateContent.Replace("<##Subtotal##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ShoppingCart.SubTotal + order.ShoppingCart.GiftSubTotal));
                    templateContent = templateContent.Replace("<##CouponDiscount##>", "-" + ECommerce.Library.ECommerce.Utility.FormatPriceText(order.CouponDiscount));
                    templateContent = templateContent.Replace("<##ShippingCost##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ProductShipping.ProductShippingCost));
                    templateContent = templateContent.Replace("<##Tax##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.TaxAmount));
                    TblProductPurchaseOrder temporder = TblProductPurchaseOrder.GetTblProductPurchaseOrderByOrderId(order.OrderId);
                    if (temporder != null)
                        templateContent = templateContent.Replace("<##TotalAmount##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(temporder.OrderPrice));
                    //templateContent = templateContent.Replace("<##giftCardImage##>", SiteSettings.SiteBaseUrl + order.GiftCardImageUrl.Replace("~/",""));
                    //templateContent = templateContent.Replace("<##giftCardMsg##>",order.GIftCardMessage);
                    templateContent = templateContent.Replace("<##TermsAndConditionsPage##>", SiteSettings.SiteBaseUrl + "terms-and-conditions.aspx");
                    templateContent = templateContent.Replace("<##SupportPage##>", SiteSettings.SiteBaseUrl + "contact-us.aspx");
                    templateContent = templateContent.Replace("<##AccountInformationPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                    templateContent = templateContent.Replace("<##PurchaseHistoryPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                    templateContent = templateContent.Replace("<##PrivacyPolicyPage##>", SiteSettings.SiteBaseUrl + "privacy-policy.aspx");

                    templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);

                    templateContent = templateContent.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);

                    templateContent = templateContent.Replace("<##SiteName##>", SiteSettings.SiteName);

                    if (order.PaymentType == PaymentType.CreditCard)
                        val = "Credit Card";
                    else if (order.PaymentType == PaymentType.GiftCoupon)
                        val = "Gift Certificate";
                    else
                        val = "Credit Card & Gift Certificate";

                    templateContent = templateContent.Replace("<##PaymentType##>", val);

                    val = (order.OrderStatus == OrderStatus.CCSuccess) ? "Success" : "Failed";
                    templateContent = templateContent.Replace("<##OrderStatus##>", val);
                    if (val == "Success")
                        templateContent = templateContent.Replace("<##Color##>", "Green");
                    else
                        templateContent = templateContent.Replace("<##Color##>", "Red");

                    string giftCard = string.Empty;
                    if (order.GiftCardImageUrl.Length > 0)
                    {
                        giftCard = " <span><strong> Gift Card </strong></span> <br/><br /> " +
                                    " <img  src=" + SiteSettings.SiteBaseUrl + order.GiftCardImageUrl.Replace("~/", "") + " width=\"190\" height=\"70\" /><br /><br /> " + order.GIftCardMessage + "<br />";
                        templateContent = templateContent.Replace("<##GiftCard##>", giftCard);
                    }
                    else
                    {
                        templateContent = templateContent.Replace("<##GiftCard##>", "");
                    }
                    string orderItems = string.Empty;
                    foreach (CartItem item in order.ShoppingCart.CartItems)
                    {
                        string productName2 = string.Empty;
                        if (!string.IsNullOrEmpty(item.Product.ProductName2))
                            productName2 = " / " + item.Product.ProductName2;

                        string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                            + item.Product.ItemNumber + "</td><td style=\"text-align: left\">"
                            + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                        + item.Product.ProductName + productName2 + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" /> <td style=\"height: 30px; text-align: left;\">"
                            + item.Quantity + "</td>"
                        + "</td><td style=\"text-align: left; padding-left:10px;\">" +
                        ECommerce.Library.ECommerce.Utility.FormatPriceText(item.Product.ProductPrice) + "</td> <td style=\"height: 30px; text-align: right;\">"
                        + item.Quantity * item.Product.ProductPrice + "</td></tr>";
                        orderItems += temp;
                    }
                    templateContent = templateContent.Replace("<##OrderItems##>", orderItems);


                    string giftItems = string.Empty;
                    foreach (GiftItem item in order.ShoppingCart.GiftItems)
                    {
                        string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                            + item.FromName + "</td><td style=\"text-align: left\">"
                            + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                        + item.FromEmailAddress + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" />"
                        + "</td><td style=\"text-align: right;\">" +
                        ECommerce.Library.ECommerce.Utility.FormatPriceText(item.ItemTotal) + "</td></tr>";
                        giftItems += temp;
                    }
                    templateContent = templateContent.Replace("<##GiftCertificate##>", giftItems);

                    string featuredItems = string.Empty;
                    ECommerce.Library.DataStructure.ReadWriteCustomCollection<Product> featuredProducts = Product.FeaturedProducts(3);

                    if (featuredProducts != null && featuredProducts.Count > 0)
                    {
                        featuredItems = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >"
                                        + "<tr><td><img alt=\"Recommendations\" src=\"<##SiteUrl##>images/recommend.gif\" width=\"180\" border=\"0\" height=\"33\" /></td></tr>"
                                        + "<tr style=\"background-color:#f5f4f4;border-left: solid 1px #D0D0D0;border-right: solid 1px #D0D0D0\"><td >"
                                        + "<table style=\"width: 100%;text-align: center;padding-top: 10px;\" cellpadding=\"0\" cellspacing=\"0\" >";
                        foreach (Product item in featuredProducts)
                        {
                            string temp = "<tr><td style=\"vertical-align: top;\">"
                               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\" >"
                               + "<tr><td style=\"text-align: center; vertical-align: top\">"
                               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\">"
                               + "<tr><td style=\"border: 1px solid #cccccc; padding: 0px;\">"
                               + "<a href=\"" + SiteSettings.SiteBaseUrl + item.ProductUrl.Replace("~/", "") + "\" target=\"_blank\"><img src=\""
                               + SiteSettings.SiteBaseUrl + ImageResizer.CheckImageMissing(item.ProductImageSmallThumbnail, SiteSettings.NoImageSmallThumbnailUrl).Replace("~/", "") + "\" width=\"60\" height=\"60\" border=\"0\" /></a>"
                               + "</td></tr></table></td></tr><tr>"
                               + "<td style=\"text-align: center; color: #000000;\" valign=\"top\">"
                               + "<a href=\"" + SiteSettings.SiteBaseUrl + item.ProductUrl.Replace("~/", "") + "\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                               + item.ProductName + "</a></b></td>"
                              + "</tr></table></td></tr><tr><td style=\"vertical-align: top;\">&nbsp;</td></tr>";
                            featuredItems += temp;
                        }
                        featuredItems += "</table></td></tr><tr><td>"
                            + "<img alt=\"Box Bottom\" src=\"<##SiteUrl##>images/box_bevel_180_botfull.gif\" width=\"180\" border=\"0\" height=\"12\" />"
                            + "</td></tr></table>";

                    }

                    templateContent = templateContent.Replace("<##FeaturedItems##>", featuredItems);
                    templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    return templateContent;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return string.Empty;
        }
       private static string GenerateInvoiceEmailBody(ProductPurchaseOrder order, String brandImageUrl)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(_invoiceEmailTemplateFilePath)))
            {
                try
                {
                    StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(_invoiceEmailTemplateFilePath));
                    string templateContent = reader.ReadToEnd();
                    reader.Close();
                    string val = string.Empty;

                    templateContent = templateContent.Replace("<##OrderNumber##>", order.OrderNumber);
                    templateContent = templateContent.Replace("<##ReceiptDate##>", ECommerce.Library.ECommerce.Utility.FormatDateTime(order.OrderDate));
                    templateContent = templateContent.Replace("<##BillingEmailAddress##>", order.BillingAddress.EmailAddress);
                    templateContent = templateContent.Replace("<##BillingFirstName##>", order.BillingAddress.FirstName);
                    templateContent = templateContent.Replace("<##BillingLastName##>", order.BillingAddress.LastName);
                    templateContent = templateContent.Replace("<##BillingAddressLine1##>", order.BillingAddress.AddressLine1);
                    templateContent = templateContent.Replace("<##BillingAddressLine2##>", order.BillingAddress.AddressLine2);
                    templateContent = templateContent.Replace("<##ShippingEmailAddress##>", order.ShippingAddress.EmailAddress);
                    templateContent = templateContent.Replace("<##ShippingFirstName##>", order.ShippingAddress.FirstName);
                    templateContent = templateContent.Replace("<##ShippingLastName##>", order.ShippingAddress.LastName);
                    templateContent = templateContent.Replace("<##ShippingAddressLine1##>", order.ShippingAddress.AddressLine1);
                    templateContent = templateContent.Replace("<##ShippingAddressLine2##>", order.ShippingAddress.AddressLine2);
                    templateContent = templateContent.Replace("<##Subtotal##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ShoppingCart.SubTotal + order.ShoppingCart.GiftSubTotal));
                    templateContent = templateContent.Replace("<##CouponDiscount##>", "-" + ECommerce.Library.ECommerce.Utility.FormatPriceText(order.CouponDiscount));
                    templateContent = templateContent.Replace("<##ShippingCost##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.ProductShipping.ProductShippingCost));
                    templateContent = templateContent.Replace("<##Tax##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(order.TaxAmount));
                    TblProductPurchaseOrder temporder = TblProductPurchaseOrder.GetTblProductPurchaseOrderByOrderId(order.OrderId);
                    if (temporder != null)
                        templateContent = templateContent.Replace("<##TotalAmount##>", ECommerce.Library.ECommerce.Utility.FormatPriceText(temporder.OrderPrice));
                    //templateContent = templateContent.Replace("<##giftCardImage##>", SiteSettings.SiteBaseUrl + order.GiftCardImageUrl.Replace("~/",""));
                    //templateContent = templateContent.Replace("<##giftCardMsg##>",order.GIftCardMessage);
                    templateContent = templateContent.Replace("<##TermsAndConditionsPage##>", SiteSettings.SiteBaseUrl + "terms-and-conditions.aspx");
                    templateContent = templateContent.Replace("<##SupportPage##>", SiteSettings.SiteBaseUrl + "contact-us.aspx");
                    templateContent = templateContent.Replace("<##AccountInformationPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                    templateContent = templateContent.Replace("<##PurchaseHistoryPage##>", SiteSettings.SiteBaseUrl + "login.aspx");
                    templateContent = templateContent.Replace("<##PrivacyPolicyPage##>", SiteSettings.SiteBaseUrl + "privacy-policy.aspx");

                    templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);

                    if (string.IsNullOrEmpty(brandImageUrl))
                    {
                        templateContent = templateContent.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    }
                    else
                    {
                        templateContent = templateContent.Replace("<##SiteLogo##>", brandImageUrl);
                    }

                    templateContent = templateContent.Replace("<##SiteName##>", SiteSettings.SiteName);

                    if (order.PaymentType == PaymentType.CreditCard)
                        val = "Credit Card";
                    else if (order.PaymentType == PaymentType.GiftCoupon)
                        val = "Gift Certificate";
                    else
                        val = "Credit Card & Gift Certificate";

                    templateContent = templateContent.Replace("<##PaymentType##>", val);

                    val = (order.OrderStatus == OrderStatus.CCSuccess) ? "Success" : "Failed";
                    templateContent = templateContent.Replace("<##OrderStatus##>", val);
                    if (val == "Success")
                        templateContent = templateContent.Replace("<##Color##>", "Green");
                    else
                        templateContent = templateContent.Replace("<##Color##>", "Red");

                    string giftCard = string.Empty;
                    if (order.GiftCardImageUrl.Length > 0)
                    {
                        giftCard = " <span><strong> Gift Card </strong></span> <br/><br /> " +
                                    " <img  src=" + SiteSettings.SiteBaseUrl + order.GiftCardImageUrl.Replace("~/", "") + " width=\"190\" height=\"70\" /><br /><br /> " + order.GIftCardMessage + "<br />";
                        templateContent = templateContent.Replace("<##GiftCard##>", giftCard);
                    }
                    else
                    {
                        templateContent = templateContent.Replace("<##GiftCard##>", "");
                    }
                    string orderItems = string.Empty;
                    foreach (CartItem item in order.ShoppingCart.CartItems)
                    {
                        string productName2 = string.Empty;
                        if (!string.IsNullOrEmpty(item.Product.ProductName2))
                            productName2 = " / " + item.Product.ProductName2;

                        string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                            + item.Product.ItemNumber + "</td><td style=\"text-align: left\">"
                            + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                        + item.Product.ProductName + productName2 + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" /> <td style=\"height: 30px; text-align: left;\">"
                            + item.Quantity + "</td>"
                        + "</td><td style=\"text-align: left; padding-left:10px;\">" +
                        ECommerce.Library.ECommerce.Utility.FormatPriceText(item.Product.ProductPrice) + "</td> <td style=\"height: 30px; text-align: right;\">"
                        + item.Quantity * item.Product.ProductPrice + "</td></tr>";
                        orderItems += temp;
                    }
                    templateContent = templateContent.Replace("<##OrderItems##>", orderItems);


                    string giftItems = string.Empty;
                    foreach (GiftItem item in order.ShoppingCart.GiftItems)
                    {
                        string temp = "<tr><td style=\"height: 30px; text-align: left;\">"
                            + item.FromName + "</td><td style=\"text-align: left\">"
                            + "<a href=\"#\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                        + item.FromEmailAddress + "</a><br /><img src=\"" + SiteSettings.SiteBaseUrl + "images/spacer.gif\" width=\"20\" height=\"1\" />"
                        + "</td><td style=\"text-align: right;\">" +
                        ECommerce.Library.ECommerce.Utility.FormatPriceText(item.ItemTotal) + "</td></tr>";
                        giftItems += temp;
                    }
                    templateContent = templateContent.Replace("<##GiftCertificate##>", giftItems);

                    string featuredItems = string.Empty;
                    ECommerce.Library.DataStructure.ReadWriteCustomCollection<Product> featuredProducts = Product.FeaturedProducts(3);

                    if (featuredProducts != null && featuredProducts.Count > 0)
                    {
                        featuredItems = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >"
                                        + "<tr><td><img alt=\"Recommendations\" src=\"<##SiteUrl##>images/recommend.gif\" width=\"180\" border=\"0\" height=\"33\" /></td></tr>"
                                        + "<tr style=\"background-color:#f5f4f4;border-left: solid 1px #D0D0D0;border-right: solid 1px #D0D0D0\"><td >"
                                        + "<table style=\"width: 100%;text-align: center;padding-top: 10px;\" cellpadding=\"0\" cellspacing=\"0\" >";
                        foreach (Product item in featuredProducts)
                        {
                            string temp = "<tr><td style=\"vertical-align: top;\">"
                               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\" >"
                               + "<tr><td style=\"text-align: center; vertical-align: top\">"
                               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\">"
                               + "<tr><td style=\"border: 1px solid #cccccc; padding: 0px;\">"
                               + "<a href=\"" + SiteSettings.SiteBaseUrl + item.ProductUrl.Replace("~/", "") + "\" target=\"_blank\"><img src=\""
                               + SiteSettings.SiteBaseUrl + ImageResizer.CheckImageMissing(item.ProductImageSmallThumbnail, SiteSettings.NoImageSmallThumbnailUrl).Replace("~/", "") + "\" width=\"60\" height=\"60\" border=\"0\" /></a>"
                               + "</td></tr></table></td></tr><tr>"
                               + "<td style=\"text-align: center; color: #000000;\" valign=\"top\">"
                               + "<a href=\"" + SiteSettings.SiteBaseUrl + item.ProductUrl.Replace("~/", "") + "\" target=\"_blank\" style=\"color: #0658b5; text-decoration: none;\">"
                               + item.ProductName + "</a></b></td>"
                              + "</tr></table></td></tr><tr><td style=\"vertical-align: top;\">&nbsp;</td></tr>";
                            featuredItems += temp;
                        }
                        featuredItems += "</table></td></tr><tr><td>"
                            + "<img alt=\"Box Bottom\" src=\"<##SiteUrl##>images/box_bevel_180_botfull.gif\" width=\"180\" border=\"0\" height=\"12\" />"
                            + "</td></tr></table>";

                    }

                    templateContent = templateContent.Replace("<##FeaturedItems##>", featuredItems);
                    templateContent = templateContent.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    return templateContent;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return string.Empty;
        }

       public static bool SendEmailToAFriend(Product product, string senderName, string senderEmail,
            string friendName, string friendEmail)
        {
            try
            {
                string fullEmailText = string.Empty;

                MailSettings mailSettings = new MailSettings();
                mailSettings.ServerAddress = SiteSettings.EmailServer;
                mailSettings.Port = SiteSettings.EmailPort;
                mailSettings.UserName = SiteSettings.EmailUserName;
                mailSettings.Password = SiteSettings.EmailPassword;
                mailSettings.AdminMail = SiteSettings.EmailAdminAddress;
                mailSettings.SupportMail = SiteSettings.EmailSupportAddress;
                mailSettings.SenderName = SiteSettings.CompanyName;

                CustomCollection<TblEmailTemplate> tblEmailTemplate = TblEmailTemplateExtended.GetEmailTemplateByTitle(EmailTemplateType.EmailToAFriend.ToString());
                string mailText = string.Empty;
                string mailSubject = SiteSettings.CompanyName + " :  To A Friend";
                if (tblEmailTemplate.Count > 0)
                {
                    mailText = tblEmailTemplate[0].EmailBody;
                    mailSubject = tblEmailTemplate[0].EmailSubject;
                    mailText = mailText.Replace("<##SiteUrl##>", SiteSettings.SiteBaseUrl);
                    mailText = mailText.Replace("<##SiteLogo##>", SiteSettings.SiteLogoMain);
                    mailText = mailText.Replace("<##SiteName##>", SiteSettings.SiteName);
                    mailText = mailText.Replace("<##FriendName##>", friendName);
                    mailText = mailText.Replace("<##SenderName##>", senderName);
                    mailText = mailText.Replace("<##ProductName##>", product.ProductName);
                    mailText = mailText.Replace("<##ProductUrl##>", Path.Combine(SiteSettings.SiteBaseUrl, product.ProductUrl.Substring(2)));

                    NameValueCollection items = new NameValueCollection();
                    items.Add("ReceiverName", friendName);
                    items.Add("ReceiverEmail", friendEmail);
                    items.Add("Subject", mailSubject);
                    MailSender.SendHtmlMaill(mailSettings, mailText, items);

                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
